package dbinit;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.product.model.Product;
import core.product.model.ProductAddress;
import core.util.HibernateCoreUtil;

public class InitProductAddress 
{
	public static ProductAddress getProductAddressByProduct(Product p)
	{
		ProductAddress pa = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction(); 
			List <ProductAddress> pas = session.createQuery("from ProductAddress pa where pa.product=:p").setEntity("p",p).list();
		    Iterator <ProductAddress> pasItr = pas.iterator(); 
			while(pasItr.hasNext())
			{
				pa = pasItr.next() ;
				break ;
			}
			
			 transaction.commit();
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return pa ;
	}
	/*
	 * private String  addressLine1;
	private String  addressLine2;
	private String phone;
	private String zip ;
	 */
	public static Long doinit(String sku , String addressLine1 , String addressLine2, String phone , String zip)
	{
		Transaction transaction = null;
		ProductAddress pa = null ;
		Long uuid = null;
		Product p = InitProduct.getProductByUuid(InitProduct.getProductIdBySku(sku));
		if(p != null)
		{
			Session session = HibernateCoreUtil.getSessionFactory().openSession();	
			try
			{	
				pa = getProductAddressByProduct(p);
				transaction = session.beginTransaction();
				if(pa == null)
				{
					pa = new ProductAddress();
					pa.setProduct(p);
					pa.setAddressLine1(addressLine1);
					pa.setAddressLine2(addressLine2);
					pa.setPhone(phone);
					pa.setZip(zip);	
					uuid = (Long) session.save(pa); 
					
				}
				else
				{
					pa.setAddressLine1(addressLine1);
					pa.setAddressLine2(addressLine2);
					pa.setPhone(phone);
					pa.setZip(zip);
					session.merge(pa); 
					uuid = pa.getUuid();
				}
				transaction.commit();	
			}
			catch(HibernateException he)
			{
				he.printStackTrace();
			}
			finally 
			{
				session.close();
			}
		}
		else
		{
			System.out.println("Product with sku "+sku +" not found");
		}
		return uuid ;
	}
}
